import fs from "fs"
import jwt from "jsonwebtoken"

const cert = fs.readFileSync('./jwt_rsa_private_key.pem');
const pubcert = fs.readFileSync('./jwt_rsa_public_key.pem');

export interface TokenPayload {
	userId: number
	userOpenId: string
}

export const encode = (payload: any, signOptions: jwt.SignOptions = {algorithm: 'RS256', expiresIn: '7d'}) => {
	return new Promise((resolve, reject) => {
		console.log('signOptions=>', signOptions)
		jwt.sign(payload, cert, Object.assign({
			algorithm: 'RS256', expiresIn: '7d'
		}, signOptions), function(err, token) {
			if (err) {
				reject(err);
			} else {
				resolve(token);
			}
		});
	});
}

export const decode = (token: string) => {
	return new Promise((resolve, reject) => {
		jwt.verify(token, pubcert, {
			algorithms: ['RS256']
		}, function(err, payload) {
			if (err) {
				reject(err);
			} else {
				resolve(payload);
			}
		});
	});
}